﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Common.Framework.Core.Extension
{
    /// <summary>
    /// Path扩展类
    /// </summary>
    public static class PathExtension
    {
        /// <summary>
        /// 组合绝对路径和相对路径,返回一个新的绝对路径
        /// </summary>
        /// <param name="absolutePath">绝对路径</param>
        /// <param name="virtualPath">相对路径</param>
        /// <returns></returns>
        public static string CombineAbsoluteAndVirtualPath(string absolutePath, string virtualPath)
        {
            string splicingResult = string.Empty;
            if (!Path.IsPathRooted(virtualPath))
            {
                //匹配相对路径，匹配需要向上推的目录层数
                Regex regex = new Regex(@"^\\|([.]{2})");
                int backUp = regex.Matches(virtualPath).Count + 1;
                List<string> pathes = absolutePath.Split("\\".ToCharArray()).ToList();
                pathes.RemoveRange(pathes.Count - backUp, backUp);
                //匹配文件名，匹配需要附加的目录层数
                List<string> virtualPaths =virtualPath.Split("\\".ToCharArray()).ToList();
                virtualPaths.RemoveAll(s => s.Contains(".."));

                pathes.AddRange(virtualPaths);

                //驱动器地址取绝对路径中的驱动器地址
                pathes[0] = Path.GetPathRoot(absolutePath);
                foreach (string p in pathes)
                {
                    splicingResult = Path.Combine(splicingResult, p);
                }
            }
            return splicingResult;
        }
    }
}
